package com.itheima.common.interceptor;

import com.itheima.common.entity.ResultCode;
import com.itheima.common.exception.IhrmException;
import com.itheima.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author IntelliJ IDEA
 * @Date 2020/11/4 20:35
 * @Version 1.0
 *
 * JWT  鉴权拦截器
 */
@Configuration
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    private static final String JWTSTR="Bearer ";

    /**
     * 前置拦截
     * 前端发送过来的请求头 Authorization
     * 请求头以Bearer+空格
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器啦!");
        String authorization = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(authorization) && authorization.startsWith(JWTSTR)){
            String token = authorization.replace(JWTSTR, "");
            //解析token中的apis
            Claims claims = JwtUtils.parseJwt(token);
            if(claims!=null){
                return true;
                //获取apis
                //TODO... 真实的生产环境会将用户的api进行配置到数据表，
//                String apis= (String) claims.get("apis");
//                HandlerMethod h=(HandlerMethod) handler;
//                RequestMapping annotation = h.getMethodAnnotation(RequestMapping.class);
//                String name=annotation.name();
//                if(StringUtils.contains(apis,name)){
//                    return true;
//                }
            }else{
                throw new IhrmException(ResultCode.UNAUTHORISE);
            }
        }
        throw new IhrmException(ResultCode.UNAUTHENTICATED);
    }
}
